<?php
/**
 * 用户认证系统
 * 提供登录、登出、权限检查等功能
 */

class Auth {
    private $db;
    
    public function __construct() {
        $this->db = getDB();
    }
    
    /**
     * 用户登录
     */
    public function login($username, $password) {
        // 防止SQL注入
        $username = trim($username);
        
        // 查询用户信息
        $sql = "SELECT * FROM users WHERE username = ? AND status = 1";
        $user = $this->db->querySingle($sql, [$username]);
        
        if (!$user) {
            return ['success' => false, 'message' => '用户名或密码错误'];
        }
        
        // 验证密码
        if (password_verify($password, $user['password'])) {
            // 登录成功，更新最后登录时间
            $this->updateLastLogin($user['id']);
            
            // 设置会话
            $this->setSession($user);
            
            return ['success' => true, 'message' => '登录成功', 'user' => $user];
        } else {
            return ['success' => false, 'message' => '用户名或密码错误'];
        }
    }
    
    /**
     * 用户登出
     */
    public function logout() {
        // 销毁会话
        $_SESSION = [];
        
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        
        session_destroy();
    }
    
    /**
     * 检查用户是否已登录
     */
    public function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
    
    /**
     * 获取当前用户信息
     */
    public function getCurrentUser() {
        if (!$this->isLoggedIn()) {
            return null;
        }
        
        $sql = "SELECT * FROM users WHERE id = ?";
        return $this->db->querySingle($sql, [$_SESSION['user_id']]);
    }
    
    /**
     * 获取用户角色
     */
    public function getUserRole() {
        $user = $this->getCurrentUser();
        return $user ? $user['role'] : 'guest';
    }
    
    /**
     * 检查权限
     */
    public function checkPermission($requiredRole) {
        $userRole = $this->getUserRole();
        
        $roles = ['guest', 'user', 'super_admin'];
        $userLevel = array_search($userRole, $roles);
        $requiredLevel = array_search($requiredRole, $roles);
        
        return $userLevel >= $requiredLevel;
    }
    
    /**
     * 重定向到登录页面
     */
    public function redirectToLogin() {
        header('Location: /public/login.php');
        exit;
    }
    
    /**
     * 重定向到无权限页面
     */
    public function redirectToNoPermission() {
        header('Location: /public/no_permission.php');
        exit;
    }
    
    /**
     * 要求登录
     */
    public function requireLogin() {
        if (!$this->isLoggedIn()) {
            $this->redirectToLogin();
        }
    }
    
    /**
     * 要求权限
     */
    public function requirePermission($requiredRole) {
        $this->requireLogin();
        
        if (!$this->checkPermission($requiredRole)) {
            $this->redirectToNoPermission();
        }
    }
    
    /**
     * 更新最后登录时间
     */
    private function updateLastLogin($userId) {
        $sql = "UPDATE users SET last_login = NOW() WHERE id = ?";
        $this->db->execute($sql, [$userId]);
    }
    
    /**
     * 设置会话信息
     */
    private function setSession($user) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = $user['role'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['login_time'] = time();
    }
    
    /**
     * 注册新用户
     */
    public function register($userData) {
        // 验证必填字段
        $required = ['username', 'password', 'email', 'full_name'];
        foreach ($required as $field) {
            if (empty($userData[$field])) {
                return ['success' => false, 'message' => "{$field} 不能为空"];
            }
        }
        
        // 检查用户名是否已存在
        $sql = "SELECT id FROM users WHERE username = ?";
        $existing = $this->db->querySingle($sql, [$userData['username']]);
        if ($existing) {
            return ['success' => false, 'message' => '用户名已存在'];
        }
        
        // 检查邮箱是否已存在
        $sql = "SELECT id FROM users WHERE email = ?";
        $existing = $this->db->querySingle($sql, [$userData['email']]);
        if ($existing) {
            return ['success' => false, 'message' => '邮箱已存在'];
        }
        
        // 密码加密
        $hashedPassword = password_hash($userData['password'], PASSWORD_DEFAULT);
        
        // 插入用户数据
        $sql = "INSERT INTO users (username, password, email, full_name, department, position, phone, role) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        $params = [
            $userData['username'],
            $hashedPassword,
            $userData['email'],
            $userData['full_name'],
            $userData['department'] ?? '',
            $userData['position'] ?? '',
            $userData['phone'] ?? '',
            $userData['role'] ?? 'user'
        ];
        
        try {
            $this->db->execute($sql, $params);
            return ['success' => true, 'message' => '用户注册成功'];
        } catch (Exception $e) {
            return ['success' => false, 'message' => '注册失败: ' . $e->getMessage()];
        }
    }
    
    /**
     * 修改密码
     */
    public function changePassword($userId, $currentPassword, $newPassword) {
        $user = $this->db->querySingle("SELECT password FROM users WHERE id = ?", [$userId]);
        
        if (!$user || !password_verify($currentPassword, $user['password'])) {
            return ['success' => false, 'message' => '当前密码错误'];
        }
        
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        $sql = "UPDATE users SET password = ? WHERE id = ?";
        
        try {
            $this->db->execute($sql, [$hashedPassword, $userId]);
            return ['success' => true, 'message' => '密码修改成功'];
        } catch (Exception $e) {
            return ['success' => false, 'message' => '密码修改失败'];
        }
    }
}

// 创建全局认证实例
function getAuth() {
    static $auth = null;
    if ($auth === null) {
        $auth = new Auth();
    }
    return $auth;
}
?>
